//
//  PageNode.m
//  iOSCodeLearning
//
//  Created by TFAppleWork-Summer on 2018/3/14.
//  Copyright © 2018年 Ace. All rights reserved.
//

#import "PageNode.h"
#import "ColorViewController.h"
@interface PageNode()<ASPagerDataSource,ASPagerDelegate>

@property (nonatomic, assign) CGRect savedFrame ;

/**
 滑动之前的index
 */
@property (nonatomic, assign) NSInteger originalIndex;

/**
 滑动后的目标下标
 */
@property (nonatomic, assign) NSInteger targetIndex;


@end


@implementation PageNode

-(instancetype)init{
    if (self = [super init]) {
        [self addSubnode:self.pagerNode];
    }
    return self;
}
-(void)layout{
    [super layout];
    self.savedFrame = self.frame;
    self.pagerNode.frame = self.bounds;
}


-(NSInteger)currentPageIndex{
    return self.pagerNode.currentPageIndex;
}

-(void)scrollToViewVontrollerAtIndex:(NSInteger)index animated:(BOOL)animated{
    NSAssert([self numberOfPagesInPagerNode:self.pagerNode] >= index, @"out of range");
    [self.pagerNode scrollToPageAtIndex:index animated:animated];
}


-(UIViewController *)viewControllerAtPageIndex:(NSInteger)index{
    ASCellNode *cellNode = [self.pagerNode nodeForPageAtIndex:index];
    UIViewController *vc = [cellNode valueForKey:@"_viewController"];
    return vc;
}

-(void)reloadDataWithCompletion:(void (^)(void))completion{
    [self.pagerNode reloadDataWithCompletion:completion];
}


#pragma mark - ASPagerNodeDelegate
- (NSInteger)numberOfPagesInPagerNode:(ASPagerNode *)pagerNode{
    if (self.delegate && [self.delegate respondsToSelector:@selector(numberOfPagesInPageNode:)]) {
       return  [self.delegate numberOfPagesInPageNode:self];
    }
    return 0;
}

-(ASCellNodeBlock)pagerNode:(ASPagerNode *)pagerNode nodeBlockAtIndex:(NSInteger)index{
    __weak PageNode *weak_self = self;
    return ^{
        ASCellNode *page = [[ASCellNode alloc] initWithViewControllerBlock:^UIViewController * _Nonnull{
            if (self.delegate && [self.delegate respondsToSelector:@selector(pageNode:viewControllAtIndex:)]) {
                return [weak_self.delegate pageNode:self viewControllAtIndex:index];
            }
            return nil;
        } didLoadBlock:^(__kindof ASDisplayNode * _Nonnull node) {
            
        }];
        return page;
    };
}

#pragma mark - UIScrollViewDelegate
/**
 将要开始拖拽的时候
 */
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    self.originalIndex = self.currentPageIndex;
}

/**
 将要结束拖拽的时候
 */
-(void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
    
    // 确定目标位置的下标
    self.targetIndex = (*targetContentOffset).x/CGRectGetWidth(scrollView.frame);
    
    // 当前下标改为目标下标
    self.currentPageIndex = self.targetIndex;
    
    
    //将要结束拖拽的时候将 将要显示的vc的下标传出去
    if (self.delegate && [self.delegate respondsToSelector:@selector(pageNode:didSelectViewControllerAtIndex:)]) {
        [self.delegate pageNode:self didSelectViewControllerAtIndex:self.targetIndex];
    }
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
   
    //scrollview 此刻的偏移量
    CGFloat  currentScrollOffset = scrollView.contentOffset.x;
    //滚动之前的所有在下标的偏移量
    CGFloat  currentIndexOffset = self.originalIndex * CGRectGetWidth(scrollView.frame);
    //滚动的目标下标 (目标下标初始值为当前原始下标)
    NSInteger scrollToIndex = self.originalIndex;
    
    if (scrollView.dragging || scrollView.decelerating){
        CGFloat percent = 0.0;
        if (currentScrollOffset > currentIndexOffset)
        {// 此刻的偏移量 > 之前的偏移量  == 右滚动
            // 1 计算滚动的百分比
            percent = (currentScrollOffset - currentIndexOffset) / CGRectGetWidth(scrollView.frame);
            // 2 计算目标下标
            if (scrollView.dragging)
            {// 向右边拖拽
                scrollToIndex = self.originalIndex + 1;
            }
            if (scrollView.decelerating)
            {// 向右边减速滚动
                scrollToIndex = self.targetIndex;
            }
        }
        else if (currentIndexOffset > currentScrollOffset)
        {// 之前的偏移量 > 此刻的偏移量 == 左滚动
            // 1 计算滚动百分比
            percent = (currentIndexOffset - currentScrollOffset) / CGRectGetWidth(scrollView.frame);
            // 2 计算下标
            if (scrollView.dragging)
            {// 向左边拖拽
                scrollToIndex = self.originalIndex-1 <= 0 ? 0 : self.originalIndex -1;
            }
            if (scrollView.decelerating)
            {
                scrollToIndex = self.targetIndex;
            }
        }
        
        if (scrollToIndex != self.originalIndex)
        {// 如果目标位置和当前位置不一样
            percent = percent / labs(scrollToIndex - self.originalIndex);
        }
        
        if (self.delegate && [self.delegate respondsToSelector:@selector(pageNode:scrollToIndex:byPercent:)]) {
            [self.delegate pageNode:self scrollToIndex:scrollToIndex byPercent:percent];
        }
    }
}

#pragma mark - lazy-load
-(ASPagerNode*)pagerNode{
    if (!_pagerNode) {
        _pagerNode = [[ASPagerNode alloc] init];
        _pagerNode.frame = self.bounds;
        _pagerNode.delegate = self;
        _pagerNode.dataSource = self;
        _pagerNode.allowsAutomaticInsetsAdjustment = YES;
        
        ASRangeTuningParameters minimumRenderParams = { .leadingBufferScreenfuls = 0.0, .trailingBufferScreenfuls = 0.0 };
        ASRangeTuningParameters minimumPreloadParams = { .leadingBufferScreenfuls = 0.0, .trailingBufferScreenfuls = 0.0 };
        [_pagerNode setTuningParameters:minimumRenderParams forRangeMode:ASLayoutRangeModeMinimum rangeType:ASLayoutRangeTypeDisplay];
        [_pagerNode setTuningParameters:minimumPreloadParams forRangeMode:ASLayoutRangeModeMinimum rangeType:ASLayoutRangeTypePreload];
        
        ASRangeTuningParameters fullRenderParams = { .leadingBufferScreenfuls = 0.0, .trailingBufferScreenfuls = 0.0 };
        ASRangeTuningParameters fullPreloadParams = { .leadingBufferScreenfuls = 0.0, .trailingBufferScreenfuls = 0.0 };
        [_pagerNode setTuningParameters:fullRenderParams forRangeMode:ASLayoutRangeModeFull rangeType:ASLayoutRangeTypeDisplay];
        [_pagerNode setTuningParameters:fullPreloadParams forRangeMode:ASLayoutRangeModeFull rangeType:ASLayoutRangeTypePreload];

    }
    return _pagerNode;
}




@end
